﻿using DotNet.Utilities;
using JinfuyuanProject.Entity;
using JinfuyuanProject.Entity.Filter;
using JinfuyuanProject.Entity.Models;
using JinfuyuanProject.Entity.ViewModels;
using JinfuyuanProject.Repository;
using JinfuyuanProject.Repository.Interface;
using JinfuyuanProject.Repository.Repository;
using JinfuyuanProject.Service.Interface;
using MongoDB.Bson.IO;
using MongoDB.Driver;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Newtonsoft.Json;
using JsonConvert = Newtonsoft.Json.JsonConvert;


namespace JinfuyuanProject.Service.Service
{

    public class ManagerService : IManagerService
    {
        private readonly IMParturientRepository _mongodbParturientRepository;
        private readonly IStaffRepository _staffRepository;
        private readonly IParturientRepository _parturientRepository;

        public ManagerService(IMParturientRepository mParturientRepository, IStaffRepository staffRepository, IParturientRepository parturientRepository)
        {
            _mongodbParturientRepository = mParturientRepository;
            _staffRepository = staffRepository;
            _parturientRepository = parturientRepository;
        }

        #region 业务方法
        public ResMessage Query(ManagerFilter filter)
        {
            var staffData = _staffRepository.GetList().Where(x=>x.RoleId==2);
            var parturientsData = _parturientRepository.GetList();
            var mongodbParturients = _mongodbParturientRepository.GetList().ToList();

            // 总数
            int count = staffData.Count();

            var query = from staff in staffData
                        join parturient in parturientsData on staff.Id equals parturient.Salesman into allParturientGroup
                        from parturient in allParturientGroup.DefaultIfEmpty()
                        group parturient by staff into grouped
                        select new
                        {
                            staff = grouped.Key,
                            parturientCount = grouped.Count(p => p != null),

                            parturients = grouped.Where(p => p != null).ToList()
                        };


            //  LINQ 合并 
            var result = query
           .AsEnumerable() // 转换到内存中
           .GroupBy(x => x.staff.Numbers) // 根据员工的号码进行分组
           .Select(group => new ManagerVM
           {
               Number = group.First().staff.Numbers, // 取分组中的第一个员工
               Name = group.First().staff.Name,
               Phone = group.First().staff.Phone,
               SuccessCount = group.First().parturientCount, // 如果该组中有 parturient 记录，表示该员工有“发展”数量
               AllCount = mongodbParturients.Count(m => m.SalesmanNumbers == group.Key), // 计算该销售人员的全部数量


               // 填充每个员工的parturient列表
               managerParturientVM = group.First().parturients.Select(p => new ManagerParturientVM
               {
                   ParturientName = p.ParturientName,
                   // CreateTime = FormatJsonDate(p.CreateTime)
                   CreateTime = p.CreateTime.ToString(),
               }).ToList(),
               // 填充MongoDBParturient数据
               managerMongoDBParturientVMm = mongodbParturients
                .Where(m => m.SalesmanNumbers == group.Key)
                .Select(m => new ManagerParturientVM
                {
                    ParturientName = m.ParturientName,
                    //CreateTime = FormatJsonDate(m.CreateTime) // 这里是MongoDB中的CreateTime
                    CreateTime = m.CreateTime.ToString()
                }).ToList()
           });


            if (filter.Name != null&&filter.Name!="")
            {
                result = result.Where(x => x.Name.Contains(filter.Name)); // 使用 Contains 来模糊匹配，避免精确匹配问题
            }
            if (filter.Phone != ""&&filter.Phone!=null)
            {
                result = result.Where(x => x.Phone ==filter.Phone);
            }
            //做分页
            if (filter.page != 0 && filter.limit != 0)
                result = result.OrderBy(x => x.Number).Skip((filter.page - 1) * filter.limit).Take(filter.limit);

            return ResMessage.Success(result,count);
        }
        public ResMessage GetData(string data)
        {
            string correctedData = data.Replace("&quot;", "\"");
            correctedData = correctedData.Trim('"');
            ManagerVM managerVM = JsonConvert.DeserializeObject<ManagerVM>(correctedData);
            // 如果 managerVM 为空或其中的字段为空，进行适当处理
            if (managerVM == null)
            {
                // 处理空数据的情况
                return null;
            }
            // 使用字典来按年/月统计每月的记录数
            Dictionary<int, List<int>> yearlyData = new Dictionary<int, List<int>>();

            foreach (var item in managerVM.managerMongoDBParturientVMm)
            {
                // 解析CreateTime字段
                var time=item.CreateTime;
                string[] formats = { "yyyy/M/d H:mm:ss", "yyyy/MM/dd H:mm:ss", "yyyy/M/d HH:mm:ss", "yyyy-MM-dd HH:mm:ss" };
                DateTime createTime;

               DateTime.TryParseExact(item.CreateTime, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out createTime);

               

                int year = createTime.Year;
                int month = createTime.Month;

                // 如果该年份还没有记录，初始化12个月份的数据
                if (!yearlyData.ContainsKey(year))
                {
                    yearlyData[year] = new List<int>(new int[12]); // 初始化12个月份，每个月的计数为0
                }

                // 增加该月的计数
                yearlyData[year][month - 1]++;
            }

            // 将数据转换成你需要的格式
            var result = yearlyData.Select(kv => new { Year = kv.Key, Counts = kv.Value }).ToList();

            // 输出结果
            var resultList = result.Select(item => new { item.Year, item.Counts }).ToList();


            // 使用字典来按年/月统计每月的记录数
            Dictionary<int, List<int>> yearlyData1 = new Dictionary<int, List<int>>();


            foreach (var item in managerVM.managerParturientVM)  // 修改为 managerParturientVM
            {
                // 解析CreateTime字段
                string[] formats = { "yyyy/M/d H:mm:ss", "yyyy/MM/dd H:mm:ss", "yyyy/M/d HH:mm:ss", "yyyy-MM-dd HH:mm:ss" };
                DateTime createTime;

                DateTime.TryParseExact(item.CreateTime, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out createTime);

                int year2 = createTime.Year;
                int month2 = createTime.Month;

                // 如果该年份还没有记录，初始化12个月份的数据
                if (!yearlyData1.ContainsKey(year2))
                {
                    yearlyData1[year2] = new List<int>(new int[12]); // 初始化12个月份，每个月的计数为0
                }

                // 增加该月的计数
                yearlyData1[year2][month2 - 1]++;
            }

            // 将数据转换成你需要的格式
            var result2 = yearlyData1.Select(kv => new { Year = kv.Key, Counts = kv.Value }).ToList();

            // 输出结果
            var resultList2 = result2.Select(item => new { item.Year, item.Counts }).ToList();
            if (resultList == null)
                resultList[0].Counts[0] = 0;
            if (resultList2 == null)
                resultList2[0].Counts[0] = 0;
            // 返回处理后的结果
            return ResMessage.Success(new
            {
                ResultList = resultList,
                ResultList2 = resultList2
            });
        }


        

        #endregion

    }
}
